#include <stdio.h>
#include <GL/glut.h>
#include <string.h>
#include "global.h"

extern int win_width;
extern int win_height;

extern GLfloat frame[WIN_HEIGHT][WIN_WIDTH][3]; 

void save_image() {
  FILE *fp;
  char fname[32];
  const int maxVal=255;
  register int y;
  unsigned char *pixels;
  
  strcpy(fname, "scene.ppm");
  printf("Saving image %s: %d x %d\n", fname, win_width, win_height);
  fp = fopen(fname, "wb");
  if (!fp) {
    printf("Unable to open file '%s'\n",fname);
    return;
  }
  fprintf(fp, "P6\n");
  fprintf(fp, "%d %d\n", win_width, win_height);
  fprintf(fp, "%d\n", maxVal);
  
  pixels = new unsigned char [3*win_width];
  
  for (y = win_height - 1; y >= 0; y--) {
#if 1
    glReadPixels(0, y, win_width, 1, GL_RGB, GL_UNSIGNED_BYTE,
		 (GLvoid *) pixels);
#else
	for (int j=0;j<win_width;j++){
		pixels[3*j]=frame[y][j][0]*255;
		pixels[3*j+1]=frame[y][j][1]*255;
		pixels[3*j+2]=frame[y][j][2]*255;
	}
#endif
	fwrite(pixels, 3, win_width, fp);
  }
  fclose(fp);
}

void histogram_normalization() {
  GLfloat max_val = 0.0;
  int i, j;

  for (i=0; i<win_height; i++) 
    for (j=0; j<win_width; j++) {
      if (frame[i][j][0] > max_val) max_val = frame[i][j][0];
      if (frame[i][j][1] > max_val) max_val = frame[i][j][1];
      if (frame[i][j][2] > max_val) max_val = frame[i][j][2];
    }

  for (i=0; i<win_height; i++) 
    for (j=0; j<win_width; j++) {
      frame[i][j][0] /= max_val;
      frame[i][j][1] /= max_val;
      frame[i][j][2] /= max_val;
    }
}
